<?php

class client{
	
	// Define variables
	private $ID_CLIENT;
	private $NAME;
	private $USERNAME;
	private $PASSWORD;
	
	// Connection with database and instance creation
	private $DB;
	public function __construct() {
		$config = config::getInstance();
		$this->DB = $config->config_values['database']['db_prefix'];
	}
	
	// Getters and setters functions
  	public function setID_CLIENT($value) {
  		$this->ID_CLIENT = $value;
  	}
	public function getID_CLIENT() {
  		return $this->ID_CLIENT;
  	}
	public function setNAME($value) {
  		$this->NAME = $value;
  	}
	public function getNAME() {
  		return $this->NAME;
  	}
	public function setUSERNAME($value) {
  		$this->USERNAME = $value;
  	}
	public function getUSERNAME() {
  		return $this->USERNAME;
  	}
	public function setPASSWORD($value) {
  		$this->PASSWORD = $value;
  	}
	public function getPASSWORD() {
  		return $this->PASSWORD;
  	}

	// General functions:
  	public function load($id)
	{
		$db = db::getInstance();
		$sql = "SELECT * FROM ".$this->DB."client WHERE ID_CLIENT=".$id;

		foreach ($db->query($sql) as $row) {
			$this->setID_CLIENT($row['ID_CLIENT']);
			$this->setNAME($row['NAME']);
			$this->setUSERNAME($row['USERNAME']);
			$this->setPASSWORD($row['PASSWORD']);
		}
	    $db = null; 
	    return true;			
  	}

  	public function insert(){}

  	public function modify($id){}

  	public function delete($id){}
  	
  	// JSON function:
	public function jsonList($id){
		try {
    		$db = db::getInstance();
			$sql = "SELECT * FROM ".$this->DB."client WHERE ID_CLIENT=".$id;
			$sth=$db->prepare($sql);
			$sth->execute();
			$recordset = array();
			$recordset = $sth->fetchAll(PDO::FETCH_ASSOC);
			return $recordset;			
		} catch (Exception $e) {
  			return false;
		}		
	}
  	
  	// Session control
    public function validateUser($user, $pass) {
		try {
			$db = db::getInstance();
			$sql = "SELECT id_client,username FROM ".$this->DB."client WHERE username='".$user."' AND password=MD5('".$pass."')";
	    	$row=$db->query($sql);
	    	if ($row->fetchColumn() > 0) {
	    		foreach ($db->query($sql) as $row) {
					$this->startSession($row[0]);
	    		}			
	    	}
	    	else 
	    	{
	    		return "Incorrect username or password";
	    	}
		    $db = null; 
    		return true;
		} catch (Exception $e) {
  			return "Error connecting: ".$e;
		}		
	}  	
	
	public function startSession($id) {
	    $_SESSION['id']=$id;
		return true;
	}
  	
	public function verifySession() {
		if(!isset($_SESSION['id'])){
			return false;
		} else {
			return true;
		}
	}
  	
}
?>